//****************************************************************
// Autor:   Gustavo Castro
//       
// Seccion: 10
// Nombre del Archivo: huffmanTree.java
// Fecha de Modificacion: 
// Descripcion:
// Arbol de Huffman. Código obtenido del libro de clase. 
// se modificó la clase print y se agregó un HashMap para guardar 
// las codificaciones respectivas de cada caracter
// ***************************************************************

package hojatrabajo6;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author cristian
 */
public class huffmanTree implements Comparable{

    BinaryTree root; // root of tree
    int totalWeight;     // weight of tree
    Map<String,String> map = new HashMap<String,String>();       

    
    public huffmanTree(leaf e)
    // post: construct a leaf with associated character
    {
	root = new BinaryTree(e);
	totalWeight = e.frequency;
    }
    public huffmanTree(huffmanTree left, huffmanTree right)
    // pre: left and right non-null
    // post: merge two trees together and merge their weights
    {
	this.totalWeight = left.totalWeight + right.totalWeight;
	root = new BinaryTree(null,left.root,right.root);
    }

    public int compareTo(Object other)
    // pre: other is non-null
    // post: return integer reflecting relation between values
    {
	huffmanTree that = (huffmanTree)other;
	return this.totalWeight - that.totalWeight;
    }

    public boolean equals(Object that)
    // post: return true if this and that are same tree instance
    {
	return this == that;
    }
    
    public void print()
    // post: print out strings associated with characters in tree
    {
	print(this.root,"");
    }
           

    protected void print(BinaryTree r, String representation)
    // post: print out strings associated with chars in tree r,
    //       prefixed by representation
    {
	if (!r.left().isEmpty())
	{   // interior node
	    print(r.left(),representation+"0"); // append a 0
	    print(r.right(),representation+"1"); // append a 1
	} else { // leaf; print encoding
	    leaf e = (leaf)r.value();
	    System.out.println("Codificacion de "+e.ch+" es "+representation+" (frecuencia: "+e.frequency+")");
            map.put(representation,String.valueOf(e.ch));
            
	}
    }

    
}
